package com.tianji.learning.util;

import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Data
public class DelayedTask<T> implements Delayed {

    /**
     * 数据
     * */
    private T data;
    /**
     * 任务的截止时间
     * */
    private long deadlineMillis;

    public DelayedTask(T data, long expire, TimeUnit unit){
        this.data = data;
        this.deadlineMillis = System.currentTimeMillis() + unit.toMillis(expire);
    }

    /**
     * 获取延迟任务的剩余延迟时间
     * */
    @Override
    public long getDelay(TimeUnit unit) {
        return this.deadlineMillis - System.currentTimeMillis();
    }

    /**
     * 比较两个延迟任务的延迟时间，判断执行顺序
     * */
    @Override
    public int compareTo(Delayed o) {
        return (int)(this.getDelay(TimeUnit.SECONDS) - o.getDelay(TimeUnit.SECONDS));
    }


}
